   
function MyPromise(fn){  
     // fn = (resolve) => { resole() }  这是用户传过来的处理程序

     // Promise resolve时的回调函数
     this.cbs = [];

         
     // 传递给处理程序的resolve
     // 这里直接往实例上挂个data
     // 然后把onResolvedCallback数组里的函数依次执行一遍就可以
     const resolve = (value) => {
        setTimeout(()=>{
            this.data = value;
            this.cbs.forEach(cb => cb(value));
        })
     }
     
     // 执行用户传进的函数
     // 并把resolve方法交给用户执行
     // 同步方法
     fn(resolve);
}



MyPromise.prototype.then = function (onResolved) {

    //Promise2
    return new MyPromise((resolve) => {
        //往promise1的cbs数组push了一个函数,这个函数等promise1被resolve会执行
        this.cbs.push(() => {
                const res = onResolved(this.data); 
                if (res instanceof MyPromise) {  //user promise
                    res.then(resolve); //把promise2的resolve函数压入cbs
                } else {
                    // 如果是普通值 就直接resolve
                    // 依次执行cbs里的函数 并且把值传递给cbs
                    resolve(res);
                }
        });
    });

};
  


const fn = (resolve) => {
    setTimeout(() => {
      resolve(1);
    }, 500);
}

const promise1 = new MyPromise(fn);

promise1.then((res) => {
      console.log(res);
      //把user_promise返回,以便继续调用
      return new MyPromise((resolve) => {
        setTimeout(() => {
          resolve(2);
        }, 500);
      });
})
.then(console.log);
  
